/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-03 14:14:47
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import com.joysuch.wwyt.bp.bean.BpManufacturingTechAddBean;
import com.joysuch.wwyt.bp.bean.BpManufacturingTechListBean;
import com.joysuch.wwyt.bp.bean.BpMonitoringPointBean;
import com.joysuch.wwyt.bp.entity.BpDeviceFacilityCollection;
import com.joysuch.wwyt.bp.entity.BpDeviceFacilityMonitoringPoint;
import com.joysuch.wwyt.bp.entity.BpManufacturingTech;
import com.joysuch.wwyt.bp.entity.BpMonitoringPointRel;
import com.joysuch.wwyt.bp.enums.DeviceFacilityTypes;
import com.joysuch.wwyt.bp.repository.BpDeviceFacilityCollectionDao;
import com.joysuch.wwyt.bp.repository.BpDeviceFacilityMonitoringPointDao;
import com.joysuch.wwyt.bp.repository.BpManufacturingTechDao;
import com.joysuch.wwyt.bp.repository.BpMonitoringPointRelDao;
import com.joysuch.wwyt.bp.service.BpDeviceFacilityCollectionService;
import com.joysuch.wwyt.bp.service.BpManufacturingTechService;
import com.joysuch.wwyt.core.bean.BaseAttachmentBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.repository.BaseImageRespositoryDao;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.mh.BizUtils;
import com.joysuch.wwyt.mh.entity.MhMonitoringPoint;
import com.joysuch.wwyt.mh.repository.MhMonitoringPointDao;
import com.joysuch.wwyt.mh.service.MhMonitoringPointService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class BpManufacturingTechServiceImpl implements BpManufacturingTechService {

    @Autowired
    private BaseImageRespositoryDao baseImageRespositoryDao;
    @Autowired
    private BpManufacturingTechDao dao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private BpMonitoringPointRelDao relDao;
    @Autowired
    private MhMonitoringPointDao mhMonitoringPointDao;
    @Autowired
    private BpDeviceFacilityCollectionService bpDeviceFacilityCollectionService;
    @Autowired
    private BpDeviceFacilityMonitoringPointDao bpDeviceFacilityMonitoringPointDao;
    @Autowired
    private BpDeviceFacilityCollectionDao bpDeviceFacilityCollectionDao;
    @Autowired
    private MhMonitoringPointService mhMonitoringPointService;

    @Value("${wwyt.base.serverUrl}")
    private String serverUrl;

    @Override
    public String add(BpManufacturingTechAddBean entity) {
        String errorMessage = null;
        BpManufacturingTech tech = new BpManufacturingTech();
        tech.setName(entity.getName());
        tech.setDescription(entity.getDescription());
        tech.setFinalProduct(entity.getFinalProduct());
        tech.setFinalProductForm(entity.getFinalProductForm());
        tech.setInterminateProduct(entity.getInterminateProduct());
        tech.setInterminateProductForm(entity.getInterminateProductForm());
        tech.setIsKeyMonitoringDangerTech(entity.getIsKeyMonitoringDangerTech());
        tech.setReactionType(entity.getReactionType());
        tech.setSafeControlBaseRequiment(entity.getSafeControlBaseRequiment());
        tech.setSafetyValveUsageStat(entity.getSafetyValveUsageStat());
        tech.setTechDangerFeature(entity.getTechDangerFeature());
        if (entity.getImage() != null) {
            tech.setTechProgressPicture(entity.getImage().getId());
        }
        tech.setOrgCode(bizCodeGeneratorFacade.gongYiLiuCheng());
        BpManufacturingTech save = dao.save(tech);
        List<Long> pointId = entity.getPointId();
        if (pointId != null) {
            for (Long aLong : pointId) {
                BpMonitoringPointRel bpMonitoringPointRel = new BpMonitoringPointRel();
                bpMonitoringPointRel.setRefType("manufacturing_tech");
                bpMonitoringPointRel.setRefId(save.getId());
                bpMonitoringPointRel.setMonitoringPointId(aLong);
                //检查监测点是否已被关联
                //工艺流程可绑定别人已经绑定的监测点无需确认是否关联
               /* errorMessage = mhMonitoringPointService.checkMhMointPoint(aLong, save.getId());
                if (StringUtils.isBlank(errorMessage)) {
                    relDao.save(bpMonitoringPointRel);
                }*/
                relDao.save(bpMonitoringPointRel);
            }
        }
        //  addOrUpdateDeviceFacilityCollection(save, pointId);
        return errorMessage;
    }

    private void addOrUpdateDeviceFacilityCollection(BpManufacturingTech save, List<Long> pointId) {
        // 保存到集中统一的表中
        BpDeviceFacilityCollection device = bpDeviceFacilityCollectionService.addOrUpdateOtherDevice(
                DeviceFacilityTypes.GONG_YI_LIU_CHENG, save.getId(), null, save.getName(), null, null, null);
        // 绑定监测点
        bpDeviceFacilityCollectionService.bindDeviceAndMonitorPointsByIds(device, pointId);
    }

    @Override
    public String update(BpManufacturingTechAddBean entity) {
        String errorMessage = null;
        relDao.deleteByRefTypeAndRefId("manufacturing_tech", entity.getId());
        BpManufacturingTech tech = dao.findById(entity.getId()).get();
        // System.out.println(entity.getId());
        tech.setName(entity.getName());
        tech.setDescription(entity.getDescription());
        tech.setFinalProduct(entity.getFinalProduct());
        tech.setFinalProductForm(entity.getFinalProductForm());
        tech.setInterminateProduct(entity.getInterminateProduct());
        tech.setInterminateProductForm(entity.getInterminateProductForm());
        tech.setIsKeyMonitoringDangerTech(entity.getIsKeyMonitoringDangerTech());
        tech.setReactionType(entity.getReactionType());
        tech.setSafeControlBaseRequiment(entity.getSafeControlBaseRequiment());
        tech.setSafetyValveUsageStat(entity.getSafetyValveUsageStat());
        tech.setTechDangerFeature(entity.getTechDangerFeature());
        if (entity.getImage() != null) {
            tech.setTechProgressPicture(entity.getImage().getId());
        }
        BpManufacturingTech save = dao.save(tech);
        List<Long> pointId = entity.getPointId();
        for (Long aLong : pointId) {
            BpMonitoringPointRel bpMonitoringPointRel = new BpMonitoringPointRel();
            bpMonitoringPointRel.setRefType("manufacturing_tech");
            bpMonitoringPointRel.setRefId(save.getId());
            bpMonitoringPointRel.setMonitoringPointId(aLong);
            if (StringUtils.isBlank(errorMessage)) {
                relDao.save(bpMonitoringPointRel);
            }
        }
        // addOrUpdateDeviceFacilityCollection(save, pointId);
        return errorMessage;
    }

    @Override
    public List<BpManufacturingTechListBean> findByPage(Pageable page) {
        page = PageDataUtils.addOrderByDesc(page, "id");
        Page<BpManufacturingTech> all = dao.findAll(page);
        ArrayList<BpManufacturingTechListBean> list = new ArrayList<>();
        for (BpManufacturingTech b : all) {
                BpManufacturingTechListBean bean = new BpManufacturingTechListBean();
                bean.setId(b.getId());
                bean.setName(b.getName());
                bean.setReactionType(b.getReactionType());
                bean.setIsKeyMonitoringDangerTech(b.getIsKeyMonitoringDangerTech());
                bean.setIsKeyMonitoringDangerTechName(BizUtils.translateYesNoToChinese(b.getIsKeyMonitoringDangerTech()));
                List<BpMonitoringPointRel> manufacturing_tech = relDao.findByRefTypeAndRefId("manufacturing_tech",
                        b.getId());
            String name = "";
                for (BpMonitoringPointRel manufacturingTech : manufacturing_tech) {
                    MhMonitoringPoint one = mhMonitoringPointDao.getOne(manufacturingTech.getMonitoringPointId());
                name += one.getName() + "、";
                }
            if (name != null && name.length() > 0) {
                bean.setPointName(name.substring(0, name.length() - 1));
                }
                list.add(bean);
            }
        return list;
    }

    @Override
    public void delete(Long id) {
        relDao.deleteByRefTypeAndRefId("manufacturing_tech", id);
        dao.deleteById(id);
        bpDeviceFacilityCollectionService.delteByDeviceTypeAndDeviceId(DeviceFacilityTypes.GONG_YI_LIU_CHENG, id);
    }

    @Override
    public BpManufacturingTech findById(Long id) {
        return dao.findById(id).get();
    }

    @Override
    public List<BpMonitoringPointBean> findAll(Pageable page) {
        /*
         * QBpDeviceFacilityCollection bpDeviceFacilityCollection =
         * QBpDeviceFacilityCollection.bpDeviceFacilityCollection;
         * Predicate predicate = bpDeviceFacilityCollection.isNotNull();
         * predicate = 1 ==0 ? predicate : ExpressionUtils.and(predicate, bpDeviceFacilityCollection.deviceTypeId.eq(new
         * Long(1)));
         */
        List<BpDeviceFacilityCollection> byPage = bpDeviceFacilityCollectionDao.findAll();
        ArrayList<BpMonitoringPointBean> list = new ArrayList<>();
        for (BpDeviceFacilityCollection b : byPage) {
            BpMonitoringPointBean bpMonitoringPointBean = new BpMonitoringPointBean();
            if (b.getDeviceTypeId() == 1) {
                List<BpDeviceFacilityMonitoringPoint> all = bpDeviceFacilityMonitoringPointDao.findAll();
                bpMonitoringPointBean.setFacilityId(b.getDeviceId());
                bpMonitoringPointBean.setFacilityName(b.getName());
                for (BpDeviceFacilityMonitoringPoint bpDeviceFacilityMonitoringPoint : all) {
                    if (bpDeviceFacilityMonitoringPoint.getDeviceId() == b.getId()) {
                        MhMonitoringPoint one1 = mhMonitoringPointDao
                                .getOne(bpDeviceFacilityMonitoringPoint.getMonitoringPointId());
                        bpMonitoringPointBean.setId(one1.getId());
                        bpMonitoringPointBean.setAction(one1.getAlarmAction());
                        bpMonitoringPointBean.setMinitoringTypeName(one1.getMhMonitoringType().getName());
                        bpMonitoringPointBean.setName(one1.getName());
                        bpMonitoringPointBean.setRealtimeValue(one1.getRealtimeValue());
                        bpMonitoringPointBean.setPointCode(one1.getPointCode());
                        if (one1.getMhMonitoringType().getId() == 3) {
                            bpMonitoringPointBean.setFloor(one1.getHighValue2());
                            bpMonitoringPointBean.setUpperLimit(one1.getLowValue2());
                        } else {
                            bpMonitoringPointBean.setFloor(one1.getLevel2Threshold());
                            bpMonitoringPointBean.setUpperLimit(one1.getLevel1Threshold());
                        }
                    }
                }
                if (bpMonitoringPointBean.getId() != null) {
                    list.add(bpMonitoringPointBean);
                }
            }
        }
        return list;
    }

    // @Override
    public BpManufacturingTechAddBean getById(Long id) {
        BpManufacturingTech entity = dao.getOne(id);
        BpManufacturingTechAddBean tech = new BpManufacturingTechAddBean();
        tech.setName(entity.getName());
        tech.setOrgCode(entity.getOrgCode());
        tech.setDescription(entity.getDescription());
        tech.setFinalProduct(entity.getFinalProduct());
        tech.setFinalProductForm(entity.getFinalProductForm());
        tech.setInterminateProduct(entity.getInterminateProduct());
        tech.setInterminateProductForm(entity.getInterminateProductForm());
        tech.setIsKeyMonitoringDangerTech(entity.getIsKeyMonitoringDangerTech());
        tech.setReactionType(entity.getReactionType());
        tech.setSafeControlBaseRequiment(entity.getSafeControlBaseRequiment());
        tech.setSafetyValveUsageStat(entity.getSafetyValveUsageStat());
        tech.setTechDangerFeature(entity.getTechDangerFeature());
        BaseAttachmentBean baseAttachmentBean = new BaseAttachmentBean();
        baseAttachmentBean.setId(entity.getTechProgressPicture());
        baseAttachmentBean.setDownloadUrl(serverUrl + "/image/view?id=" + entity.getTechProgressPicture());
        tech.setImage(baseAttachmentBean);

        tech.setId(entity.getId());
        List<BpMonitoringPointRel> all1 = relDao.findByRefTypeAndRefId("manufacturing_tech", id);
        ArrayList<BpMonitoringPointBean> objects = new ArrayList<>();
        for (BpMonitoringPointRel bpMonitoringPointRel : all1) {
            BpMonitoringPointBean byId = mhMonitoringPointService.getByIds(bpMonitoringPointRel.getMonitoringPointId());
            objects.add(byId);
        }
        tech.setBpMonitoringPointBeans(objects);
        return tech;
    }

}
